from datetime import datetime, timedelta
import sqlite3, time, json
import requests as rq
import pandas as pd
from os import sep
import time
from threading import Thread

default_info = json.load(open('DaBai_v1' + sep + 'baseinfo.json', 'rb'))


def fdata(timedelta_):
    days = timedelta_.days
    seconds = timedelta_.seconds
    hours, seconds = divmod(seconds, 3600)
    minutes, seconds = divmod(seconds, 60)
    minutes += bool(seconds)
    temp, minutes = divmod(minutes, 60)
    hours += temp
    temp, hours = divmod(hours, 24)
    days += temp
    return (f'{days}天' if days else '') + (f'{hours}小时' if hours else '') + (f'{minutes}分钟' if minutes else '')


# 换一种思路实现：提醒强度/提醒等级---提前设置好n个等级，-1级=不提醒，然后每次提醒等级-1，最后...
tip_grades = [
    timedelta(minutes=10),
    timedelta(minutes=15),
    timedelta(minutes=30),
    timedelta(hours=1),
    timedelta(hours=2),
    timedelta(hours=6),
    timedelta(hours=12),
    timedelta(days=1),
    timedelta(days=2),
    timedelta(days=4),
]  # 最高等级：9

close = True


def async_send(func, *args, **kwargs):
    while not close:
        pass
    time.sleep(default_info["default_close_gap_send_time"])
    func(*args, **kwargs)


# 思路，每过30秒查一次表，查 作业表 进行提醒， 查 tip 表进行提醒，先实现 tip
while True:
    print('循环中' + '.' * (datetime.now().second % 7) + ' ' * 8, end='\r', flush=True)
    try:
        conn = sqlite3.connect('db.sqlite3')
        close = False
        c = conn.cursor()

        cursor_tip = c.execute("SELECT `name`, `begin` from DaBai_v1_tip")
        for row in cursor_tip:
            if datetime.now() >= pd.to_datetime(row[1]):
                t = Thread(target=async_send, args=(rq.post, default_info["self_server_url"] + 'send_tip/'),
                           kwargs=dict(data={'name': f'{row[0]}'}))
                t.start()

        cursor_task_hand_in = c.execute("SELECT `name`, `end` from DaBai_v1_task")

        for row in cursor_task_hand_in:  # 自动提交
            if datetime.now() >= pd.to_datetime(row[1]):
                t = Thread(target=async_send, args=(rq.post, default_info["self_server_url"] + 'hand_in_task/',),
                           kwargs=dict(data={'name': f'{row[0]}'}))
                t.start()

        cursor_task_remind = c.execute("SELECT `name`, `end`, `tip_grade` from DaBai_v1_task;")

        for row in cursor_task_remind:  # 自动提醒
            row = row[:]
            if row[2] >= 0 and pd.to_datetime(row[1]) - tip_grades[row[2]] <= datetime.now():
                # rq.post(default_info["self_server_url"] + 'remind_task_interface/',
                #         data={
                #             'name': f'{row[0]}',
                #             'last_time': fdata(pd.to_datetime(row[1]) - datetime.now())
                #         })
                t = Thread(target=async_send, args=(rq.post, default_info["self_server_url"]+'remind_task_interface/'),
                           kwargs=dict(data={
                            'name': f'{row[0]}',
                            'last_time': fdata(pd.to_datetime(row[1]) - datetime.now())
                        }))
                t.start()
                c.execute(f"UPDATE DaBai_v1_task SET `tip_grade`=? WHERE `name`=?;", [row[2] - 1, row[0]])

        cursor_cache = c.execute("SELECT `id`, `time` from DaBai_v1_cache;")
        for row in cursor_cache:  # 删除多余默认缓存时间的无效缓存
            if datetime.now() >= pd.to_datetime(row[1]) + timedelta(minutes=default_info["cache_life"]):
                c.execute("DELETE FROM DaBai_v1_cache WHERE id=?;", [row[0]])


    except Exception as error:
        with open('outlogs.txt', 'a') as f:
            f.write(f'{datetime.now()}:::{error}\n')
    conn.commit()
    c.close()
    conn.close()
    close = True
    time.sleep(default_info["sleep_time"])
